package com.atguigu.gmall.activity.controller;


import com.atguigu.gmall.activity.redis.CacheHelper;
import com.atguigu.gmall.activity.service.ActivityService;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.service.RabbitService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillApiController {

    @Autowired
    private ActivityService activityService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    //查询
    @GetMapping("/getSeckillList")
    public List<SeckillGoods> getSeckillList(){
        return activityService.getSeckillList();
    }

    @GetMapping("/getSeckillGoods/{skuId}")
    public SeckillGoods getSecKillGoodsById(@PathVariable(name = "skuId") Long skuId){
        return activityService.getSecKillGoodsById(skuId);
    }
    //立即抢购之获取下单码、
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable(name = "skuId") Long skuId, HttpServletRequest
                                     request){
        String userId = AuthContextHolder.getUserId(request);
        //1:判断当前商品是否在活动范围之内
        SeckillGoods secKillGoods = activityService.getSecKillGoodsById(skuId);
        //   starttime < 当前时间 < endTime
        Date cur = new Date();
        if(DateUtil.dateCompare(secKillGoods.getStartTime(),cur) &&
                DateUtil.dateCompare(cur,secKillGoods.getEndTime()) ){
            //在活动范围中
            // 不用Redis来保存
            return Result.ok(MD5.encrypt(userId));
        }
        return Result.fail().message("不在活动时间中");
    }
    //立即抢购之钩子触发的开始抢购
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable(name = "skuId") Long skuId,String skuIdStr
    ,HttpServletRequest request){
//        1、判断下单码是否正确
        String userId = AuthContextHolder.getUserId(request);
        if(!StringUtils.isEmpty(skuIdStr) && MD5.encrypt(userId).equals(skuIdStr)){

////        2、判断状态位  skuId:1（本）
            String state = (String) CacheHelper.get(skuId.toString());
            if(!"1".equals(state)){
                return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
            }
////        3、发消息（用户ID：SkuId）
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                    MqConst.ROUTING_SECKILL_USER,userRecode);
////        4、Result.ok
            return Result.ok();
        }
        //下单码不正确
        return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
    }

    //查询秒杀结果
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable(name = "skuId") Long skuId,HttpServletRequest
                              request){
        String userId = AuthContextHolder.getUserId(request);
//        1、判断是否下单成功
        Object o = redisTemplate.opsForHash().get(RedisConst.SECKILL_ORDERS_USERS +
                userId, skuId.toString());
        if(null != o){
            return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
        }
//        2、判断是否抢购成功
        Object o1 = redisTemplate.opsForHash().get(RedisConst.SECKILL_ORDERS + userId,
                skuId.toString());
        if(null != o1){
            return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
        }
//        3、判断是否在排队中
        Object o2 = redisTemplate.opsForValue().get(
                RedisConst.SECKILL_USER + userId + ":"
                        + skuId);
        if(o2 == null){
            //排队中
            return Result.build(null,ResultCodeEnum.SECKILL_RUN);
        }
        // 4、抢购失败
        return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
    }
}
